package com.wh.stock.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.wh.stock.dao.StockLogMapper;
import com.wh.stock.pojo.StockLog;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import com.wh.stock.pojo.Stock;
import com.wh.stock.dao.StockMapper;
import com.wh.stock.service.IStockService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.wh.stock.dto.StockQueryDto;

import java.time.LocalDateTime;

/**
 * 业务实现类
 */
@Service
public class StockServiceImpl extends ServiceImpl<StockMapper, Stock> implements IStockService {

    @Autowired
    private StockMapper stockMapper;
    @Autowired
    private StockLogMapper stockLogMapper;

    @Override
    public IPage<Stock> findByPage(StockQueryDto stockQueryDto){
        //1.创建查询条件
        QueryWrapper<Stock> qw = new QueryWrapper<>();
        //qw.like("xxx",stockQueryDto.getXxx());
        //qw.or();
        //qw.like("xxx",stockQueryDto.getXxx());
        //2.组件分页数据
        IPage<Stock> page = new Page<>(stockQueryDto.getCurrentPage(), stockQueryDto.getPageSize());
        page.setRecords(stockMapper.findByPage(page,qw));
        page.setTotal(stockMapper.selectCount(qw));
        //3.返回

        return page;
    }

    @Override
    public void updById(Stock stock) {
        //1查到原本的库存数据
        Stock oldstock = stockMapper.selectById(stock.getId());
        //2创建一个库存记录对象
        StockLog stockLog = new StockLog();
        //3修改数据库库存
        stockMapper.updateStock(stock.getId(),stock.getStock());
        //4添加库存记录数据
        stockLog.setProcId(stock.getId());
        stockLog.setUpdBefore(oldstock.getStock());//原来的数据
        int num = stock.getStock()-oldstock.getStock();//修改的数量，修改后减去修改前
        stockLog.setUpdAfter(stock.getStock());
        stockLog.setUpdNum(num);
        //在库存记录中添加数据：  修改人，修改时备注，
        stockLog.setUpdUser(stock.getUpuser());
        stockLog.setRemark(stock.getRemark());
        stockLog.setUpdTime(LocalDateTime.now());
        stockLogMapper.insert(stockLog);
    }
}
